package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingyun.gpsinspection.purificationservice.common.utils.ConstantUtil;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.ProcessBean;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.organization.JsmOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.IBMBPMService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import sun.misc.BASE64Encoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;

/**
 * Java访问IBM REST API工具类
 * <p>
 * Created by sugongche on 2016/12/19.
 */
public class IBMBPMServiceImpl implements IBMBPMService {

    public Logger logger = LoggerFactory.getLogger(IBMBPMServiceImpl.class);

    public static final String WORKSPACEERROR = "WorkSpaceError";

    @Autowired
    private JsmOrganizationService jsmOrganizationService;

    //基础路径
    @Value("#{configProperties['baseURL']}")
    private String baseURL;

    //相对路径
    @Value("#{configProperties['relativeURI']}")
    private String relativeURI;

    //应用程序名称
    @Value("#{configProperties['processAppName']}")
    private String processAppName;
    // 查询的名称
    @Value("#{configProperties['queryName']}")
    private String queryName;
    // 待办
    @Value("#{configProperties['awaitTask']}")
    private String awaitTask;
    // 用户名
    @Value("#{configProperties['username']}")
    private String bpmUserName;
    // 密码
    @Value("#{configProperties['password']}")
    private String bpmPassword;
    //应用程序版本
    private String newestVersion;

    //应用程序ID
    private String processAppId;

    //待办任务数量
    private String size;


    /**
     * 获得当前人所属组织的所属作业区的前两个字符
     *
     * @param employeeVo
     * @return
     */
    public String getWorkSpaceNameFirstTwoLetters(EmployeeVo employeeVo) {
//        String orgId = employeeVo.getOrgId();
//        List<Organization> orgList = jsmOrganizationService.selectUpByTree(orgId);
//        //作业区名称
//        String workSpaceName = "";
//        //作业区名称的前两个字符
//        String firstTwoLetters = "";
//        //查询当前人的组织所属作业区
//        if (orgList != null && orgList.size() > 0) {
//            for (Organization organization : orgList) {
//                if (organization != null && organization.getOrgLevelId().equals(WorkInstanceLevelEnum.ORG_LEVEL_WORK_SPACE.getCode())) {
//                    workSpaceName = organization.getOrgName();
//                }
//            }
//        }
//
//        if (workSpaceName.length() >= 2) {
//            firstTwoLetters = workSpaceName.substring(0, 2);
//        } else if (workSpaceName.length() == 1) {
//            logger.error("作业区名称只有1个字符，不符合要求！");
//        } else if ("".equals(workSpaceName)) {
//            logger.error("当前登录人不属于作业区，而是属于气矿或者分公司，无法发起任务！");
//        }
//
//        return firstTwoLetters;
        return "忠县";
    }

    /**
     * 开启流程
     *
     * @param url           api的访问url
     * @param bpdId         BPD 标识:以25开头
     * @param snapshotId    Snapshot 标识:以2064开头
     * @param branchId      分支标识::以2063开头
     * @param processAppId  流程应用程序标识:以2066开头
     * @param requestMethod 请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username      用户名
     * @param password      密码
     * @param parameter     参数
     * @return
     */
    public String openBPM(String url, String bpdId, String snapshotId, String branchId, String processAppId, String requestMethod, String username, String password, String parameter) {
        // BPMAPI中开启流程的URL
        String callURL = url + "/rest/bpm/wle/v1/process?action=start";
        // BPD 标识:以25开头
        if (bpdId != null) {
            callURL = callURL + "&bpdId=" + bpdId;
        }
        // Snapshot 标识:以2064开头
        if (snapshotId != null) {
            callURL = callURL + "&snapshotId=" + snapshotId;
        }
        // 分支标识::以2063开头
        if (branchId != null) {
            callURL = callURL + "&branchId=" + branchId;
        }
        // 流程应用程序标识:以2066开头
        if (processAppId != null) {
            callURL = callURL + "&processAppId=" + processAppId;
        }
        // 参数
        if (parameter != null) {
            callURL = callURL + "&params=" + parameter;
        }
        // 执行后返回JSON
        if (callURL != null) {
            callURL = callURL + "&parts=all";
            return callRestAPI(callURL, requestMethod, username, password);
        } else {
            return null;
        }

    }


    /**
     * 开启流程
     * 请求：https://192.168.0.200:9443/rest/bpm/wle/v1/process?action=start&bpdId=25.b90b53fd-af89-4016-8eb1-f8de0bf994a9&snapshotId=2064.97ca58c9-1347-4364-ba33-b62e01297f6e&processAppId=2066.8595eceb-25b9-4234-842f-b6fd56ef6c79&parts=all
     * 方法： POST
     *
     * @param employeeVo
     * @param taskType   流程类型
     * @param username   用户名
     * @param password   密码
     * @param parameter  参数
     * @return
     */
    public String openBPM(EmployeeVo employeeVo, Short taskType, String username, String password, String parameter) {
        String firstTwoLetters = this.getWorkSpaceNameFirstTwoLetters(employeeVo);

        if (StringUtils.isNotEmpty(firstTwoLetters)) {
            // BPMAPI中开启流程的URL
            String callURL = baseURL + relativeURI + "/process?action=start";

            String bpdId = "";
            String processAppId = "";
            String snapshotId = "";


            ProcessBean bean = queryLatestVersion(firstTwoLetters, taskType, username, password);
            if (bean != null) {
                bpdId = bean.getItemID();
                processAppId = bean.getProcessAppID();
                snapshotId = bean.getSnapshotID();
            }

            // BPD 标识:以25开头
            callURL = callURL + "&bpdId=" + bpdId;
            // Snapshot 标识:以2064开头
            callURL = callURL + "&snapshotId=" + snapshotId;
            // 流程应用程序标识:以2066开头
            callURL = callURL + "&processAppId=" + processAppId;
            // 参数
            if (parameter != null) {
                callURL = callURL + "&params=" + parameter;
            }

            // 执行后返回JSON
            callURL = callURL + "&parts=all";

            return callRestAPI(callURL, "POST", username, password);
        } else {
            logger.error("当前登录人不属于作业区，而是属于气矿或者分公司，无法发起任务！");
            return WORKSPACEERROR;
        }
    }


    /**
     * 完成当前节点，往下一节点扭转
     *
     * @param url           api的访问callURL
     * @param tkiid         任务标识:
     * @param requestMethod 请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username      用户名
     * @param password      密码
     * @param parameter     参数
     */
    public String completeTask(String url, String tkiid, String requestMethod, String username, String password, String parameter) {
        // BPMAPI中完成当前节点，往下一节点扭转的URL
        String callURL = url + "/rest/bpm/wle/v1/task/" + tkiid + "?action=finish";
        //完成当前节点，往下一节点扭转中的参数
        if (parameter != null) {
            callURL = callURL + "&params=" + parameter;
        }
        // 执行后返回JSON
        if (callURL != null) {
            callURL = callURL + "&parts=all";
            return callRestAPI(callURL, requestMethod, username, password);
        } else {
            return null;
        }
    }

    /**
     * 完成当前节点，往下一节点扭转
     * 请求： https://192.168.0.200:9443/rest/bpm/wle/v1/task/849?action=finish&parts=all
     * 方法： PUT
     * 状态： 200 - OK
     * 结果： 成功
     * {status: "200",
     * data: {...}
     * }
     * 结果：失败
     * {status: "error",
     * Data:{...}
     * }
     *
     * @param username  用户名
     * @param password  密码
     * @param tkiid     任务标识:
     * @param parameter 参数
     */
    public String completeTask(String username, String password, String tkiid, String parameter) {
        // BPMAPI中完成当前节点，往下一节点扭转的URL
        String callURL = baseURL + "/rest/bpm/wle/v1/task/" + tkiid + "?action=finish";
        // 完成当前节点，往下一节点扭转中的参数
        if (parameter != null) {
            callURL = callURL + "&params=" + parameter;
        }
        // 执行后返回JSON
        callURL = callURL + "&parts=all";

        return callRestAPI(callURL, "PUT", username, password);
    }

    /**
     * 终止流程
     *
     * @param url           api的访问callURL
     * @param requestMethod 请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username      用户名
     * @param password      密码
     * @param piid          流程实例标识:
     */
    public void terminateBPM(String url, String requestMethod, String username, String password, String piid) {
        String callURL = url + "/rest/bpm/wle/v1/process/" + piid;
        callURL = callURL + "?action=terminate&parts=all";

        callRestAPI(callURL, requestMethod, username, password);
    }

    /**
     * 终止流程 请求： https://192.168.0.200:9443/rest/bpm/wle/v1/process/1920?action=terminate&parts=all
     *
     * @param username
     * @param password 密码
     * @param piid
     */
    public String terminateBPM(String username, String password, String piid) {
        String callURL = baseURL + "/rest/bpm/wle/v1/process/" + piid;
        callURL = callURL + "?action=terminate&parts=all";

        String requestMethod = "POST";

        return callRestAPI(callURL, requestMethod, username, password);
    }

    /**
     * 删除流程
     *
     * @param url           api的访问url
     * @param piid          流程实例标识:
     * @param requestMethod 请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username      用户名
     * @param password      密码
     */
    public void deleteBPM(String url, String piid, String requestMethod, String username, String password) {
        String callURL = url + "/rest/bpm/wle/v1/process/" + piid;
        callURL = callURL + "?action=delete&parts=all";

        callRestAPI(callURL, requestMethod, username, password);
    }

    /**
     * 查询流程
     *
     * @param url                 api的访问callURL
     * @param queryName           查询名称:
     * @param selectedAttributes  所选属性:
     * @param interactionFilter   交互过滤器: (待办、已办等)：
     * @param queryFilter         查询过滤器:
     * @param searchFilter        搜索过滤器:
     * @param processAppName      流程应用程序名称:
     * @param sortAttributes      排序属性:
     * @param offset              偏移量:
     * @param size                大小:
     * @param filterByCurrentUser
     * @param requestMethod       请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username            用户名
     * @param password            密码
     */
    public String queryBPM(String url, String queryName, String selectedAttributes, String interactionFilter, String queryFilter, String searchFilter, String processAppName,
                           String sortAttributes, String offset, String size, String filterByCurrentUser, String requestMethod, String username, String password) {
        String callURL = url + "/rest/bpm/wle/v1/tasks/query/";
        if (queryName != null) {
            callURL = callURL + queryName + "?";
        }
        if (selectedAttributes != null) {
            callURL = callURL + "selectedAttributes=" + selectedAttributes;
        }
        if (selectedAttributes == null && interactionFilter != null) {
            callURL = callURL + "interactionFilter=" + interactionFilter;
        } else {
            callURL = callURL + "&interactionFilter=" + interactionFilter;
        }
        if (queryFilter != null) {
            callURL = callURL + "&queryFilter=" + queryFilter;
        }
        if (searchFilter != null) {
            callURL = callURL + "&params=" + searchFilter;
        }
        if (processAppName != null) {
            callURL = callURL + "&processAppName=" + processAppName;
        }
        if (sortAttributes != null) {
            callURL = callURL + "&sortAttributes=" + sortAttributes;
        }
        if (offset != null) {
            callURL = callURL + "&offset=" + offset;
        }
        if (size != null) {
            callURL = callURL + "&size=" + size;
        }
        if (filterByCurrentUser != null) {
            callURL = callURL + "&filterByCurrentUser=" + filterByCurrentUser;
        }
        if (callURL != null) {
            return callRestAPI(callURL, requestMethod, username, password);
        } else {
            return null;
        }
    }

    /**
     * 查询待办任务（未使用）
     * 访问url=http://192.168.0.200:9080/rest/bpm/wle/v1/tasks/query/IBM.DEFAULTALLTASKSLIST_75?interactionFilter=ASSESS_AND_WORK_ON&processAppName=%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E7%AE%A1%E7%90%86"
     * 访问带版本号的url=http://192.168.0.200:9080/rest/bpm/wle/v1/tasks/query/IBM.DEFAULTALLTASKSLIST_75?interactionFilter=ASSESS_AND_WORK_ON&queryFilter=SNAPSHOT_NAME='v1.3.1'&processAppName=%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E7%AE%A1%E7%90%86
     * <p>
     * 按任务节点ID降序排列
     * https://192.168.0.200:9080/rest/bpm/wle/v1/tasks/query/IBM.DEFAULTALLTASKSLIST_75?interactionFilter=ASSESS_AND_WORK_ON&processAppName=%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E7%AE%A1%E7%90%86&sortAttributes=PI_PIID%20desc
     *
     * @param username 用户名
     * @param password 密码
     * @param version  版本
     * @throws Exception
     */
    public String queryToDoTask(String username, String password, String version) {
        String callURL = baseURL + relativeURI + "/tasks/query/IBM.DEFAULTALLTASKSLIST_75?";
        callURL += "interactionFilter=ASSESS_AND_WORK_ON";
        callURL += "&processAppName=" + processAppName;
        if (version != null && !"".equals(version)) {
            callURL += "&queryFilter=SNAPSHOT_NAME='" + version + "'";
            // 版本号为空：查询所有版本号
        }
        // 必须加待办任务查询数量：否则默认查询20个待办任务
        callURL += "&size=" + size;
        // 按流程实例ID降序查询
        callURL += "&sortAttributes=PI_PIID%20desc";
        String requestMethod = "GET";

        String result = callRestAPI(callURL, requestMethod, username, password);

        return result;
    }

    /**
     * 查询指定流程实例ID的待办任务：唯一待办任务
     * https://192.168.0.200:9443/rest/bpm/wle/v1/tasks/query/IBM.DEFAULTALLTASKSLIST_75?interactionFilter=ASSESS_AND_WORK_ON&queryFilter=PI_PIID=ID('806')&processAppName=%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E7%AE%A1%E7%90%86
     *
     * @param employeeVo
     * @param username   用户名
     * @param password   用户密码
     * @param version    版本号
     * @param piPiid     流程实例ID
     * @return
     * @throws Exception
     */
    public String queryToDoTask(EmployeeVo employeeVo, String username, String password, String version, String piPiid) {
        String firstTwoLetters = this.getWorkSpaceNameFirstTwoLetters(employeeVo);

        try {
            if (StringUtils.isNotEmpty(firstTwoLetters)) {
                String callURL = baseURL + relativeURI + "/tasks/query/IBM.DEFAULTALLTASKSLIST_75?";
                callURL += "interactionFilter=ASSESS_AND_WORK_ON";
                if (piPiid != null && !"".equals(piPiid)) {
                    callURL += "&queryFilter=PI_PIID=ID('" + piPiid + "')";
                }
                callURL += "&processAppName=" + processAppName + URLEncoder.encode("-" + firstTwoLetters, "UTF-8");
                if (version != null && !"".equals(version)) {
                    callURL += "&queryFilter=SNAPSHOT_NAME='" + version + "'";
                    // 版本号为空：查询所有版本号
                }
                // 必须加待办任务查询数量：否则默认查询20个待办任务
                if (size != null && !"".equals(size)) {
                    callURL += "&size=" + size;
                }
                // 按流程实例ID降序查询
                callURL += "&sortAttributes=PI_PIID%20desc";
                String requestMethod = "GET";

                String result = callRestAPI(callURL, requestMethod, username, password);

                return result;
            } else {
                logger.error("该人员不属于作业区，而是属于气矿或者分公司，无法查询待办！");
                return WORKSPACEERROR;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return "";
    }

    /**
     * 查询代办任务（带分页）
     *
     * @param employeeVo
     * @param username    用户名
     * @param password    用户密码
     * @param queryFilter 查询条件
     * @param limit       每页显示数据条数
     * @param offset      第几条数据开始
     * @return
     */
    public String queryToDoTask(EmployeeVo employeeVo, String username, String password, String queryFilter, Integer limit, Integer offset) {
        try {
            String firstTwoLetters = this.getWorkSpaceNameFirstTwoLetters(employeeVo);

            if (StringUtils.isNotEmpty(firstTwoLetters)) {
                String callURL = baseURL + relativeURI + "/tasks/query/IBM.DEFAULTALLTASKSLIST_75?";

                callURL += "interactionFilter=ASSESS_AND_WORK_ON";
                callURL += "&processAppName=" + processAppName + URLEncoder.encode("-" + firstTwoLetters, "UTF-8");
                callURL += "&size=" + limit;// 必须加待办任务查询数量：否则默认查询20个待办任务
                callURL += "&offset=" + offset;
                if (null != queryFilter) {
                    callURL += queryFilter;//查询条件
                }
                callURL += "&sortAttributes=PI_PIID%20desc"; // 按流程实例ID降序查询
                String requestMethod = "GET";

                String result = callRestAPI(callURL, requestMethod, username, password);

                return result;
            } else {
                logger.error("当前登录人不属于作业区，而是属于气矿或者分公司，无法查询待办！");
                return WORKSPACEERROR;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return "";
    }

    /**
     * 查询代办任务记录总条数
     * 例子：http://192.168.0.200:9080/rest/bpm/wle/v1/tasks/query/IBM.DEFAULTALLTASKSLIST_75/count?interactionFilter=ASSESS_AND_WORK_ON&processAppName=%E4%BB%BB%E5%8A%A1%E8%B0%83%E5%BA%A6%E7%AE%A1%E7%90%86&queryFilter=NAME%20LIKE%20'%E5%B9%B3%E6%9D%BF%E5%A4%84%E7%90%86'
     *
     * @param employeeVo
     * @param username    用户名
     * @param password    密码
     * @param queryFilter 查询条件
     * @return
     */
    public String queryToDoTaskCount(EmployeeVo employeeVo, String username, String password, String queryFilter) {
        try {
            String firstTwoLetters = this.getWorkSpaceNameFirstTwoLetters(employeeVo);

            if (StringUtils.isNotEmpty(firstTwoLetters)) {
                String callURL = baseURL + relativeURI + "/tasks/query/IBM.DEFAULTALLTASKSLIST_75/count?";
                callURL += "interactionFilter=ASSESS_AND_WORK_ON";
                callURL += "&processAppName=" + processAppName + URLEncoder.encode("-" + firstTwoLetters, "UTF-8");
                ;
                if (null != queryFilter) {
                    callURL += queryFilter;//查询条件
                }
                String requestMethod = "GET";

                String result = callRestAPI(callURL, requestMethod, username, password);

                return result;
            } else {
                logger.error("当前登录人不属于作业区，而是属于气矿或者分公司，无法查询待办！");
                return WORKSPACEERROR;
            }
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(), e);
        }

        return "";
    }

    /**
     * 查询公开的流程
     * 请求： https://192.168.0.200:9443/rest/bpm/wle/v1/exposed/process
     * 方法： GET
     * 状态： 200 - OK
     *
     * @param username
     * @param password
     * @return
     */
    public String queryExposedProcess(String username, String password) {
        String callURL = baseURL + relativeURI + "/exposed/process";

        String result = callRestAPI(callURL, "GET", username, password);

        return result;
    }

    /**
     * 根据任务类型查询任务最新版本的对象
     *
     * @param firstTwoLetters
     * @param taskType
     * @param username
     * @param password
     * @return
     */
    public ProcessBean queryLatestVersion(String firstTwoLetters, Short taskType, String username, String password) {
        String result = queryExposedProcess(username, password);

        if ("".equals(result)) {
            logger.info("查询公开的流程返回值为空串！");
            return null;
        } else {
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj != null) {
                String status = (String) resultObj.get("status");

                if (status != null && status.equals("200")) {
                    JSONObject dataObject = (JSONObject) resultObj.get("data");

                    JSONArray listArray = (JSONArray) dataObject.get("exposedItemsList");

                    List<ProcessBean> list = JSONArray.parseArray(JSONArray.toJSONString(listArray), ProcessBean.class);
                    //System.out.println(list);

                    ProcessBean processBean = queryLatestVersion(firstTwoLetters, taskType, list);

                    return processBean;
                } else {
                    logger.error("查询公开的流程返回状态非200！");
                    return null;
                }
            } else {
                logger.error("查询公开的流程返回值非json字符串！！");
                return null;
            }
        }
    }

    /**
     * 遍历list，获得指定程序和流程的最新版本
     *
     * @param firstTwoLetters
     * @param taskType
     * @param list
     * @return
     */
    public ProcessBean queryLatestVersion(String firstTwoLetters, Short taskType, List<ProcessBean> list) {
        if (taskType == null || list == null) {
            logger.error("taskType为null或者list为null");
            return null;
        }

        //程序名称为：任务调度管理
        List<ProcessBean> rwddglList = new ArrayList<>();
        //拼接应用程序名称：
        String processAppName = ConstantUtil.RWDDGL + "-" + firstTwoLetters;
        for (ProcessBean bean : list) {
            if (processAppName.equals(bean.getProcessAppName())) {
                rwddglList.add(bean);
            }
        }

        String display = "";
        // 巡回检查
        if (taskType == 1) {
            display = ConstantUtil.XHJC;
            // 常规操作
        } else if (taskType == 2) {
            display = ConstantUtil.CGCZ;
            // 维护保养
        } else if (taskType == 3) {
            display = ConstantUtil.WHBY;
            // 检查维修
        } else if (taskType == 4) {
            display = ConstantUtil.JCWX;
            // 分析处理
        } else if (taskType == 5) {
            display = ConstantUtil.FXCL;
            // 变更管理
        } else if (taskType == 6) {
            display = ConstantUtil.BGGL;
            // 属地监督
        } else if (taskType == 7) {
            display = ConstantUtil.SDJD;
            // 作业许可
        } else if (taskType == 8) {
            display = ConstantUtil.ZYXKGL;
            // 危害因素辨识
        } else if (taskType == 9) {
            display = ConstantUtil.WHYSBS;
            // 物料管理
        } else if (taskType == 10) {
            display = ConstantUtil.WLGL;
        } else if (taskType == 11) {
            display = ConstantUtil.RCSW;
        }

        //流程名称为display：并且有版本号，并且tip为false
        List<ProcessBean> targetProcessList = new ArrayList<>();
        for (ProcessBean bean : rwddglList) {
            if (display.equals(bean.getDisplay()) && bean.getSnapshotName() != null && bean.getTip() == false) {
                targetProcessList.add(bean);
            }
        }

        ProcessBean processBean = getMaxBean(targetProcessList);

        return processBean;
    }

    /**
     * 获取版本创建时间最大的bean
     *
     * @param list
     * @return
     */
    public ProcessBean getMaxBean(List<ProcessBean> list) {
        // list 按某个字段排序：http://bbs.csdn.net/topics/240044985
        // 经过测试，如果list只有一个元素，也可以正常运行
        Collections.sort(list, new Comparator() {
            public int compare(Object o1, Object o2) {
                int flag = 0;

                //升序排列
                if ((o1 instanceof ProcessBean) && (o2 instanceof ProcessBean)) {
                    if (((ProcessBean) o1).getSnapshotCreatedOn() != null && ((ProcessBean) o2).getSnapshotCreatedOn() != null) {
                        flag = ((ProcessBean) o1).getSnapshotCreatedOn().compareTo(((ProcessBean) o2).getSnapshotCreatedOn());
                    }
                }

                return flag;
            }
        });

        ProcessBean processBean = null;
        if (list != null && list.size() > 0) {
            processBean = list.get(list.size() - 1);
        }

        return processBean;
    }

    /**
     * 调用IBM BPM REST API
     *
     * @param urlString     api的访问url
     * @param requestMethod 请求的方式"GET"/"POST"/"PUT"/"DELETE"
     * @param username      用户名
     * @param password      用户密码
     * @return json格式的字符串
     */
    public String callRestAPI(String urlString, String requestMethod, String username, String password) {
        //打印日志
        logger.info(urlString);
        HttpURLConnection connection = null;
        String content = "";
        try {
            // 构造URL对象
            URL url = new URL(urlString);
            // 根据url打开连接
            connection = (HttpURLConnection) url.openConnection();
            // POST：检索或者创建一个资源
            // Get：检索一个资源
            // PUT: 更新一个资源
            // DELETE：删除一个资源
            connection.setRequestMethod(requestMethod);
            // 设置用户名密码
            BASE64Encoder encoder = new BASE64Encoder();
            String encodedCredential = encoder.encode((username + ":" + password).getBytes());
            // 设置请求属性
            connection.setRequestProperty("Authorization", "Basic " + encodedCredential);
            // 获取调用结果
            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            int responseCode = connection.getResponseCode();
            // BPM服务器响应成功
            if (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuffer stringBuffer = new StringBuffer();
                String line = "";
                // 如果能从流中读取内容
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                content = stringBuffer.toString();
                logger.info(content);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        return content;
    }

    /**
     * 根据指定id查询代办任务标识
     *
     * @param piid 任务id
     * @return
     */
    @Override
    public String queryBPMByPiid(EmployeeVo employeeVo, String piid) {
        try {
            String firstTwoLetters = this.getWorkSpaceNameFirstTwoLetters(employeeVo);

            if (StringUtils.isNotEmpty(firstTwoLetters)) {
                String result = queryToDoTask(employeeVo, bpmUserName, bpmPassword, null, piid);
                if (StringUtils.isBlank(result)) {
                    return null;
                }
                JSONObject resultObj = JSONObject.parseObject(result);
                // 获取data属性的值
                JSONObject dataObj = (JSONObject) resultObj.get("data");
                // 获取items属性的值
                JSONArray itemsArray = (JSONArray) dataObj.get("items");
                if (itemsArray.size() <= 0) {
                    return null;
                }
                JSONObject myjObject = itemsArray.getJSONObject(0);
                Map map = myjObject;
                return map.get("TKIID").toString();
            } else {
                logger.error("当前登录人不属于作业区，而是属于气矿或者分公司，无法查询待办！");
                return WORKSPACEERROR;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return "";
    }

    /**
     * @param piid    任务标识id
     * @param toUser  要分配的用户
     * @param toGroup 要分配的组
     * @return
     */
    @Override
    public String assignTask(String piid, String toUser, String toGroup) {
        // 向用户分配
        String user = "";
        // 向组分配
        String group = "";
        try {
            // 若要分配的用户不为空
            if (StringUtils.isNotBlank(toUser)) {
                user = "&toUser=" + toUser;
            }
            // 若要分配的组不为空
            if (StringUtils.isNotBlank(toGroup)) {
                group = "&toGroup=" + toGroup;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 访问地址
        String callURL = baseURL + relativeURI + "/task/" + piid + "?action=assign" + user + group + "&parts=all";
        String requestMethod = "PUT";
        return callRestAPI(callURL, requestMethod, bpmUserName, bpmPassword);

    }

    public void main(String[] args) throws UnsupportedEncodingException {
        /*String username = "deadmin";
        String userpass = "deadmin";
        String urlString = "http://192.168.0.200:9080/rest/bpm/wle/v1/process?action=start&bpdId=25.cc17fe3c-6bac-47cc-8c6c-4bc0790b4c3d&processAppId=2066.8595eceb-25b9-4234-842f-b6fd56ef6c79&parts=all";
        String requestMethod = "POST";
        String content= callRestAPI(urlString,requestMethod,username ,userpass);
        System.out.println(content);*/

        //doGet2("", "", "");

        /*String processAppName = URLEncoder.encode("任务调度管理", "UTF-8");
        System.out.println(processAppName);*/

        /*openBPM((short) 7, username, userpass, null);*/

        /*List<ProcessBean> list = new ArrayList<>();
        ProcessBean bean=new ProcessBean();
        bean.setSnapshotCreatedOn("11");
        bean.setTip(false);
        list.add(bean);
        bean.setSnapshotCreatedOn("22");
        bean.setTip(false);
        list.add(bean);

        // 经过测试，如果list只有一个元素，也可以正常运行
        ProcessBean processBean = getMaxBean(list);
        System.out.println(processBean.getSnapshotCreatedOn());*/
    }
}
